package top.ezzz;

import cn.hutool.core.date.DateUtil;
import com.google.protobuf.Message;
import com.google.protobuf.util.JsonFormat;
import lombok.extern.slf4j.Slf4j;
import org.noear.snack.ONode;
import org.noear.snack.core.Options;
import top.ezzz.rpc.protobuf.PersonProto;
import top.ezzz.rpc.util.MessageLemon;

import java.util.Date;

/**
 * @author ezzz
 * @since 2024/1/22 10:34
 */
@Slf4j
public class SnackTest {

    /**
     * 直接使用 snack 编解码器可以实现
     */

    public static void main(String[] args) {
        Options options = Options.def();

        //添加编码器
        options.addEncoder(Date.class, (data, node) -> {
            node.val().setString(DateUtil.format(data, "yyyy-MM-dd"));
        });

        //添加解码器
        options.addDecoder(MessageLemon.class, (node, type) -> {
            MessageLemon messageLemon = new MessageLemon();
            messageLemon.setName(node.get("name").getString());
            return messageLemon;
        });

        //添加解码器
        options.addDecoder(Message.class, (node, type) -> {
            try {
                String json = node.toJson();
                Message.Builder builder = (Message.Builder) ((Class<?>) type).getMethod("newBuilder").invoke(null);
                JsonFormat.parser().merge(json, builder);
                return builder.build();
            } catch (Exception e) {
                log.error(e.getMessage(), e);
                return null;
            }
        });

        String jsonStr = """
                 {
                    "name": "ezzz",
                    "id": 1,
                    "email": "",
                    "phones": []
                 }
                """;
        jsonStr = """
                {
                    "owner": "ezzz",
                }
                """;
        //String json = ONode.loadObj(jsonStr, options).toJson();
        //PersonProto.GetAddressBookRequest request
        ONode node = ONode.loadStr(jsonStr, options);
        PersonProto.GetAddressBookRequest request = node.toObject(PersonProto.GetAddressBookRequest.class);
        System.out.println("messageLemon = " + request);
    }
}
